from fastapi import APIRouter, Depends, HTTPException, status
from pyexpat.errors import messages

from plugins.mysql.database import get_db
from sqlalchemy.orm import Session
from fastapi.responses import JSONResponse
from models.userinfo import UserLogin, User, UserResponse, UserBase,EditUser
from typing import List
from fastapi.encoders import jsonable_encoder

router = APIRouter()


@router.get("/service/user/userinfo", response_model=List[UserBase], tags=["userinfo"])
async def get_all_users(db: Session = Depends(get_db)):
    users =  db.query(User).all()
    return JSONResponse(status_code=200, content={
        "userinfo": jsonable_encoder(users),
    })

@router.post("/service/user/edit", tags=["editor"])
async def edit_userinfo(editor: EditUser, db: Session = Depends(get_db)):
    print(editor)
    if editor is not None:
        user = db.query(User).filter(User.email == editor.email).first()
        if not user:
            raise HTTPException(status_code=404, detail="User not found")
        user.name = editor.name
        user.email = editor.email
        user.phone = editor.phone
        user.tag = editor.tag
        db.commit()
        return JSONResponse(status_code=200, content={
                "code": 200,
                "message": "User updated successfully"
            })